package com.miniapp.core.utils;


import com.miniapp.common.config.PaicFtiWebDriverConfig;
import com.miniapp.common.utils.DateUtils;
import com.miniapp.common.utils.StringUtils;
import com.miniapp.common.utils.uuid.Seq;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PaicFtiChromeDriverUtils {

    private Logger logger = LoggerFactory.getLogger(PaicFtiChromeDriverUtils.class);

    @Autowired
    private PaicFtiWebDriverConfig paicFtiWebDriverConfig;


    /**
     * 平安账号对应的 货运险浏览器
     */
    public static Map<String, ChromeDriver> paicFtiChromeAccountMap = new HashMap<>();

    /**
     * 平安货运险打开的Chrome浏览器
     */
    public static List<ChromeDriver> paicFtiChromeDriverList = new ArrayList<>();






    /**
     * 打开平安登录页面
     */
    public ChromeDriver openChrome(){
        ChromeOptions options = new ChromeOptions();
        //无头浏览器
        if("--headless".equals(paicFtiWebDriverConfig.getHeadless())){
            options.addArguments("--headless");
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-setuid-sandbox");
        }
        //webdriver路径
        System.setProperty("webdriver.chrome.driver",paicFtiWebDriverConfig.getChromedriverPath());
        ChromeDriver driver = new ChromeDriver(options);
        logger.info("打开谷歌浏览器");
        //最大化
        driver.manage().window().maximize();
        logger.info("浏览器最大化");

        // 打开登录页面
        driver.get(paicFtiWebDriverConfig.getPaicFreightTransportationInsuranceUrl());
        logger.info("打开平安登录界面");
        paicFtiChromeDriverList.add(driver);
        return driver;
    }

    /**
     * 服务停止 关闭浏览器
     */
    @PreDestroy
    public void closeChrome(){
        for (ChromeDriver chromeDriver : paicFtiChromeDriverList) {
            chromeDriver.quit();
        }
        paicFtiChromeDriverList.clear();
        paicFtiChromeAccountMap.clear();
    }

    /**
     * 退出浏览器
     * @param userName
     */
    public void closeChromeByUserName(String userName){
        if(paicFtiChromeAccountMap.containsKey(userName)){
            ChromeDriver removeChromeDriver = paicFtiChromeAccountMap.remove(userName);
            boolean remove = paicFtiChromeDriverList.remove(removeChromeDriver);
            removeChromeDriver.quit();
        }
    }


    /**
     * 截图
     * @param chromeDriver
     * @param pictureName
     */
    public void webDriverScreenshot(ChromeDriver chromeDriver,String pictureName){
        //截图保存路径
        String webDriverScreenshotPath = paicFtiWebDriverConfig.getWebDriverScreenshotPath();
        String fileName = StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(pictureName), Seq.getId(Seq.uploadSeqType), "png");
        File file = ((TakesScreenshot)chromeDriver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(file,new File(webDriverScreenshotPath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 等待获取某个元素
     * @param chromeDriver
     * @param xpath 路径
     * @param timeOutInSeconds 等待超时时间
     * @return
     */
    public static WebElement waitWebElementByXPath( ChromeDriver chromeDriver,String xpath,int timeOutInSeconds){
        WebDriverWait webDriverWait = new WebDriverWait(chromeDriver,timeOutInSeconds);
        WebElement until = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
        return until;

    }


}
